<script setup lang="ts">
import { ref } from "vue"
import dayjs from "dayjs"
import { knotApi, CompanyBillInfoApi } from "@/api/bill"
import { sumValuesForName, copyToClipboard } from "@/utils/common"
import { ElMessage } from "element-plus"
import Decimal from "decimal.js"
const dialogTableVisible = ref(false)
const timer = ref<any>(null)
const enterLists = ref<any[]>([])
const outLists = ref<any[]>([])
const enter_ids = ref<any[]>([])
const out_ids = ref<any[]>([])
const enterLength = ref<number>(0)
const outLength = ref<number>(0)
const enterCount = ref<number>(0)
const enterPriceCount = ref<number>(0)
const outCount = ref<number>(0)
const outPriceCount = ref<number>(0)
const companyName = ref<string>("")
const companyId = ref<number>(0)
const ids = ref<number>(0)
const cardNumber = ref<string>("")
const cardBank = ref<string>("")
const cardName = ref<string>("")
const wxInfo = ref<string>("")
const wxLists = ref<any>([])
const zfbInfo = ref<string>("")
const zfbLists = ref<any>([])

const currentTime = ref<string>(dayjs().format("YYYY年MM月DD日 HH时mm分ss秒"))

const getNowTime = () => {
  currentTime.value = dayjs().format("YYYY年MM月DD日 HH时mm分ss秒")
  console.log(currentTime.value)
}
const clearTimer = () => {
  console.log("clearTimer")
  window.clearInterval(timer.value)
  timer.value = null
}
const showClick = (el: any) => {
  console.log(el)

  ids.value = el.id
  CompanyBillInfo()
  companyId.value = el.company_id
  companyName.value = el.company_name
  // inListsEnter()
  // inListsOut()

  timer.value = window.setInterval(() => {
    getNowTime()
  }, 1000)
  dialogTableVisible.value = true
}

defineExpose({ showClick })

const CompanyBillInfo = () => {
  CompanyBillInfoApi({
    id: ids.value
  }).then((res: any) => {
    console.log("CompanyBillInfo", res)
    const bills = res.data.bills
    const billInventors = res.data.billInventors
    const company = res.data.company
    cardNumber.value = company.card_numbers
    cardName.value = company.card_names
    cardBank.value = company.card_banks
    wxInfo.value = company.wx_codes
    wxLists.value.push(company.wx_codes)
    zfbInfo.value = company.zfb_codes
    zfbLists.value.push(company.zfb_codes)
    enterLists.value = bills.list
    enter_ids.value = bills.ids
    enterLength.value = bills.total
    enterCount.value = sumValuesForName(bills.list, "billAmount")
    enterPriceCount.value = sumValuesForName(bills.list, "enter_discount")

    outLists.value = billInventors.list
    out_ids.value = billInventors.ids
    outLength.value = billInventors.total
    outCount.value = sumValuesForName(billInventors.list, "billAmount")
    outPriceCount.value = sumValuesForName(billInventors.list, "out_discount")
  })
}

const handleClose = () => {
  clearTimer()
  enterLists.value = []
  outLists.value = []
  enter_ids.value = []
  out_ids.value = []
  enterCount.value = 0
  enterPriceCount.value = 0
  outCount.value = 0
  outPriceCount.value = 0
  companyId.value = 0
  companyName.value = ""
  dialogTableVisible.value = false
  emit("DialogClose", true)
}
const emit = defineEmits(["DialogClose"])

// const inListsEnter = () => {
//   inListsNewApi({
//     company_id: companyId.value,
//     type: "enter"
//   }).then((res: any) => {
//     enterLists.value = res.data.list
//     enter_ids.value = res.data.ids
//     enterLength.value = res.data.total
//     enterCount.value = sumValuesForName(res.data.list, "billAmount")
//     enterPriceCount.value = sumValuesForName(res.data.list, "enter_discount")
//   })
// }
// const inListsOut = () => {
//   inListsNewApi({
//     company_id: companyId.value,
//     type: "out"
//   }).then((res: any) => {
//     outLists.value = res.data.list
//     out_ids.value = res.data.ids
//     outLength.value = res.data.total
//     outCount.value = sumValuesForName(res.data.list, "billAmount")
//     outPriceCount.value = sumValuesForName(res.data.list, "out_discount")
//   })
// }

const knot = () => {
  knotApi({
    company_id: companyId.value,
    ids: ids.value
  }).then(() => {
    ElMessage.success("修改成功")
    handleClose()
  })
}

const Bill_please = () => {
  knot()
  handleClose()
}

const formatPercentage = (value: any): string => {
  if (value == null || isNaN(value)) return "-"
  const percentage = new Decimal(value).div(1000) // 假设 1000 为基数
  return `${parseFloat(percentage.toFixed(10)).toString()}%` // 转换为浮点数并去掉末尾零
}

const formatPercentages = (PriceCount: any, PriceCounts: any) => {
  return new Decimal(PriceCount).sub(PriceCounts).toNumber()
}

const formatPercentageEnters = () => {
  // (outCount - enterCount) * 10000 - (outPriceCount - enterPriceCount)
  return parseFloat(
    new Decimal(outCount.value)
      .sub(enterCount.value)
      .mul(10000)
      .sub(outPriceCount.value - enterPriceCount.value)
      .toFixed(2)
  ).toString()
}
const formatPercentageOuts = () => {
  // (enterCount - outCount) * 10000 - (enterPriceCount - outPriceCount)
  return parseFloat(
    new Decimal(enterCount.value)
      .sub(outCount.value)
      .mul(10000)
      .sub(enterPriceCount.value - outPriceCount.value)
      .toFixed(2)
  ).toString()
}
</script>

<template>
  <el-dialog
    v-model="dialogTableVisible"
    title="账单"
    width="80%"
    :before-close="handleClose"
    destroy-on-close
    draggable
  >
    <div>
      <div class="head">
        <div class="heads-left">
          <div class="heads-icons">
            <img src="@/assets/bill/tb.png" alt="" srcset="" />
          </div>
          <div class="company-name">{{ companyName }}</div>
          <!--          <div class="company-title">专业承兑服务</div>-->
        </div>
        <div class="heads-right">{{ currentTime }}</div>
      </div>
      <div class="contents">
        <table width="100%">
          <thead class="table-header">
            <tr>
              <th>序号</th>
              <th>时间</th>
              <th>事项</th>
              <th>票号</th>
              <th>承兑人信息</th>
              <th>票面金额（万元）</th>
              <th>点数</th>
              <th>张数</th>
              <th>扣息金额</th>
              <th>返点</th>
              <th>扣息后金额</th>
            </tr>
          </thead>
          <tbody>
            <!--            入库-->
            <template v-if="enterLength > 0">
              <template v-for="(item, index) in enterLists" :key="index">
                <tr class="table-row-odd">
                  <td class="tds">{{ index + 1 }}</td>
                  <td class="tds">{{ item.enter_time }}</td>
                  <td class="tds">贴现</td>
                  <td class="tds">{{ item.billNo }}</td>
                  <td class="tds">{{ item.acceptorName }}</td>
                  <td class="tds">{{ item.billAmount }}</td>
                  <td class="tds">{{ formatPercentage(item.enter_price) }}</td>
                  <td class="tds">1</td>
                  <td class="tds">{{ item.enter_discount }}</td>
                  <td class="tds">&nbsp;</td>
                  <td class="tds">&nbsp;</td>
                </tr>
              </template>
              <tr class="table-row-odd">
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
            </template>
            <!--            出库-->
            <template v-if="outLength > 0">
              <template v-for="(item, index) in outLists" :key="index">
                <tr class="table-row-odd">
                  <td class="tds">{{ index + 1 }}</td>
                  <td class="tds">{{ item.out_time }}</td>
                  <td class="tds">买票</td>
                  <td class="tds">{{ item.billNo }}</td>
                  <td class="tds">{{ item.acceptorName }}</td>
                  <td class="tds">{{ item.billAmount }}</td>
                  <td class="tds">{{ formatPercentage(item.out_price) }}</td>
                  <td class="tds">1</td>
                  <td class="tds">&nbsp;</td>
                  <td class="tds">{{ item.out_discount }}</td>
                  <td class="tds">&nbsp;</td>
                </tr>
              </template>
              <tr class="table-row-odd">
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
            </template>
            <tr class="table-row-odd">
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td class="tds">
                <span v-if="enterCount < outCount"> 合计收款 </span>
                <span v-else-if="enterCount > outCount"> 还需回款金额 </span>
                <span v-else> &nbsp; </span>
              </td>
              <td class="tds">
                <span v-if="enterCount < outCount">
                  {{ formatPercentages(outCount, enterCount) }}
                </span>
                <span v-else-if="enterCount > outCount">
                  {{ formatPercentages(enterCount, outCount) }}
                </span>
                <span v-else> 已走平 </span>
              </td>
              <td>&nbsp;</td>
              <td class="tds">
                <span v-if="enterPriceCount < outPriceCount">合计返点 </span>
                <span v-else-if="enterPriceCount > outPriceCount"> 合计扣息金额 </span>
                <span v-else> &nbsp; </span>
              </td>
              <td class="tds">
                <span v-if="enterPriceCount > outPriceCount">
                  {{ formatPercentages(enterPriceCount, outPriceCount) }}
                </span>
                <span v-else> &nbsp; </span>
              </td>
              <td class="tds">
                <span v-if="enterPriceCount < outPriceCount">
                  {{ formatPercentages(outPriceCount, enterPriceCount) }}
                </span>
                <span v-else> &nbsp; </span>
              </td>
              <td class="tds">
                <span v-if="enterCount < outCount">
                  {{ formatPercentageEnters() }}
                  <!-- {{ (outCount - enterCount) * 10000 - (outPriceCount - enterPriceCount) }} -->
                </span>
                <span v-else-if="enterCount > outCount">
                  {{ formatPercentageOuts() }}
                  <!-- {{ (enterCount - outCount) * 10000 - (enterPriceCount - outPriceCount) }} -->
                </span>
                <span v-else> &nbsp; </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="footer">
        <div class="codes">
          <div class="code" v-if="cardNumber != '' && cardName != ''">
            <div>
              {{ cardName }} <el-icon><DocumentCopy @click="copyToClipboard(cardName)" /></el-icon>
            </div>
            <div>
              {{ cardNumber }} <el-icon><DocumentCopy @click="copyToClipboard(cardNumber)" /></el-icon>
            </div>
            <div v-if="cardBank != ''">
              {{ cardBank }} <el-icon><DocumentCopy @click="copyToClipboard(cardBank)" /></el-icon>
            </div>
          </div>
          <div v-if="wxInfo != ''">
            <el-image
              style="width: 220px; height: 220px"
              :src="wxInfo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="wxLists"
              :initial-index="1"
              fit="cover"
            />
          </div>
          <div v-if="zfbInfo != ''">
            <el-image
              style="width: 220px; height: 220px"
              :src="zfbInfo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="zfbLists"
              :initial-index="1"
              fit="cover"
            />
          </div>
        </div>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="Bill_please"> 结 账 </el-button>
        </span>
      </div>
    </div>

    <!-- <template #footer>

    </template> -->
  </el-dialog>
</template>

<style scoped lang="scss">
.head {
  height: 80px;
  width: 100%;
  background: radial-gradient(circle, #fcccbc, #f4ba97);
  display: flex;
  justify-content: space-between;
}
.heads-left {
  display: flex;
}
.heads-left .company-name {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  font-weight: bold;
  font-family: Inter, "Microsoft YaHei", serif;
}
.heads-left .company-title {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  margin-bottom: 22px;
  margin-left: 10px;
  font-size: 18px;
  font-weight: bold;
  color: #0d84ff;
  font-family: Inter, "Microsoft YaHei", serif;
}
.heads-icons {
  width: 80px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.heads-icons img {
  width: 50px;
}
.heads-right {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin-bottom: 10px;
  margin-right: 10px;
  font-size: 16px;
}

.contents .table-header {
  background-color: #eee;
  font-weight: bold;
  font-size: 20px;
  line-height: 30px;
  padding: 10px;
}
.contents .table-row-odd {
  background-color: #f5f5f5;
  font-size: 20px;
  line-height: 30px;
}
.contents .tds {
  text-align: center;
  font-size: 20px;
  line-height: 30px;
  padding: 10px;
}
.footer {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}
.codes {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .code {
    display: flex;
    flex-direction: column;
    // align-items: ;
    justify-content: space-around;
    font-size: 20px;
    font-weight: bold;
    font-family: Inter, "Microsoft YaHei", serif;
  }
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
